/*
 * Copyright (c) 2010 The Chromium Authors. All rights reserved.  Use of this
 * source code is governed by a BSD-style license that can be found in the
 * LICENSE file.
 */
var regex = /^none$/i
var hostname = document.location.host;
document.addEventListener('DOMSubtreeModified', this.runTest, false);
var getVolume = function(s){
  var metric = {'ml': 1000, 'cl':100, 'dl': 10, 'l': 1};
  var regex = /((?:\d*\.)?\d+)\s*([mcd]?l)/i;
  var match = regex.exec(s);
  if(!match)return 0;
  return parseFloat(match[1]) / metric[match[2].toLowerCase()];
};
var getPrice = function(s){
  var regex = /\$((?:\d*\.)?\d+)/i;
  var match = regex.exec(s);
  if(!match)return 0;
  return parseFloat(match[1]);
};

var compareVolume = function(col) {
  return function(a,b){var tdA = $('td',a)[col] || {}; var tdB = $('td',b)[col] || {}; return getVolume(tdA.textContent) - getVolume(tdB.textContent);};
}
var comparePrice = function(col) {
  return function(a,b){var tdA = $('td',a)[col] || {}; var tdB = $('td',b)[col] || {}; return getPrice(tdA.textContent) - getPrice(tdB.textContent);};
}

var sortTable = function(t,col){
  var $t = $(t);
  var $rows = $('tr',t);
  $firstRow = $rows.first();
  $rows = $rows.not('.legend');
  $firstRow.after($rows.sort($('td',$firstRow)[col].textContent == 'Size'? compareVolume(col) : comparePrice(col)));
}

var sortTableByClick = function(e){
  var $this = $(this);
  var $tr = $this.parent();
  while($tr[0].tagName != 'TR') $tr = $tr.parent();
  var col = $('td',$tr).index(this);
  var $table = $tr.parent();
  while($table[0].tagName != 'TABLE') $table = $table.parent();
  sortTable($table[0],col);
}

$(function(){
	// Test the text of the body element against our regular expression.
	var t = document.getElementsByTagName("table");
	var req = {show:false, host:hostname};
	if (t) {
		// Check if it is visible
		var tables = [];
		for(i=0; i < t.length; ++i) {
			var p = t[i];
			while(p != null) {
				if(regex.test(p.style.display)) {
					break;
				}
				p = p.parentElement;
				if(p == document.body) {
					tables.push(t[i]);
					break;
				}
			}
      var $p = $(t[i]);
      $fr = $('tr',$p).first();
      var cellContent = [];
      $('td',$fr).each(function(i,v){
        cellContent.push($(v).text());
      });
      var colSize = cellContent.indexOf('Size');
      var colPrice = cellContent.indexOf('Price');
      if(colSize >= 0 && colPrice >= 0) {
        var $theads = $('td',$fr);
        var $thPrice = $($theads[colPrice]);
        var $thSize = $($theads[colSize]);
        var $thPricePer = $('<td>$/L</td>');
        $thPrice.click(sortTableByClick);
        $thSize.click(sortTableByClick);
        $thPricePer.click(sortTableByClick);
        $thPrice.after($thPricePer);
        $('tr',$p).each(function(i,v){
          if(i==0)return;
          var cells = $('td',v);
          var size = getVolume($(cells[colSize]).text());
          var price = getPrice($(cells[colPrice]).text());
          var result = '$' + (price / size).toFixed(2);
          $(cells[colPrice]).after($('<td>'+result+'</td>'));
        });
      }
		}
		req.show = tables.length > 0;
	} else {
	  // No match was found.
	}
	chrome.extension.sendRequest(req, function(response) {});
	showing = req.show;
});